# encoding: utf-8

require 'net/http'
require 'net/https'
class Utility

  def self.post(uri, data={})
    uri = URI.parse(uri)
    https = Net::HTTP.new(uri.host,uri.port)
    https.use_ssl = true
    if RbConfig::CONFIG["host_os"] =~ /min/
      https.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    req = Net::HTTP::Post.new(uri.path)
    req.set_form_data data
    https.request(req).body
  end

  def self.post_j(uri, data={})
    JSON.parse(post(uri, data))
  end

  def self.get(uri, data={})
    _uir = uri
    url_params = ''
    unless data.empty?
      url_params = "?"
      data.each do |key, value|
        url_params += "#{key}=#{value}&"
      end
      url_params[-1] = ''
    end
    uri = URI.parse(URI.escape(uri + url_params))
    # uri = URI.parse(uri + url_params)
    https = Net::HTTP.new(uri.host,uri.port)
    if _uir.match(/^https:\/\//)
      https.use_ssl = true
      if RbConfig::CONFIG["host_os"] =~ /min/
        https.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
    end
    req = Net::HTTP::Get.new(uri.to_s)
    https.request(req).body
  end


  def self.get_j(uri, data={})
    JSON.parse(get(uri, data))
  end

  def self.get_q(uri, data={})
    p "开始请求:解析地址"
    result = Rack::Utils.parse_nested_query(get(uri, data))
    result
  end
end